package com.open.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.open.annotation.Limit;
import com.open.annotation.Vef;
import com.open.bean.IpWhite;
import com.open.bean.RequestRecord;
import com.open.bean.RequestToken;
import com.open.bean.vo.MessageVo;
import com.open.bean.vo.OpenVo;
import com.open.component.JwtComponent;
import com.open.result.OpenResult;
import com.open.service.IpWhiteService;
import com.open.service.OpenDictService;
import com.open.service.RequestRecordService;
import com.open.service.RequestTokenService;
import com.open.service.impl.IpWhiteServiceImpl;
import com.open.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author tanyongpeng
 * <p>des</p>
 **/
@RestController
@RequestMapping("/request/open")
@Slf4j
public class SSEController {

    @Autowired
    JwtComponent jwtComponent;

    @Autowired
    IpWhiteService ipWhiteService;

    @Autowired
    RequestRecordService requestRecordService;

    @Autowired
    RequestTokenService requestTokenService;

    @Autowired
    OpenDictService openDictService;


//    @GetMapping(value = "/send/sse/{code}/{token}/{header}/{msg}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    @ResponseBody
//    @Limit
//    public Flux<String> sse(@PathVariable String code,
//                            @PathVariable String token,
//                            @PathVariable String header,
//                            @PathVariable String msg,
//                            HttpServletRequest request) {
//
//        if (msg == null || msg.trim().isEmpty()) {
//            return Flux.error(new IllegalArgumentException("msg cannot be null or empty"));
//        }
//
//        DecodedJWT decodedJWT = tokenState(URLUtil.decode(token, Charset.defaultCharset()));
//        if (decodedJWT == null){
//            return Flux.just(OpenResult.error("网站过期请重新登录")).map(JSONUtil::toJsonStr);
//        }
//
//        String wId = jwtComponent.getUserWId(decodedJWT);
//
//        IpWhite ipWhite = ipWhiteService.lambdaQuery().eq(IpWhite::getWid, wId).one();
//
//        if (ipWhite.getIpStatus() == 1){
//            return Flux.just(OpenResult.error("当前账号被封禁")).map(JSONUtil::toJsonStr);
//        }else if(ipWhite.getIpStatus() == 3){
//            return Flux.just(OpenResult.error("当前账号正在审核，请稍等...")).map(JSONUtil::toJsonStr);
//        }
//
//        OpenVo openVo = OpenRequestUtil.vefUser(request, URLUtil.decode(header, Charset.defaultCharset()));
//
//        if (!openVo.isState()){
//            return Flux.just(OpenResult.error(openVo.getMsg())).map(JSONUtil::toJsonStr);
//        }
//
//
//        Integer msgState = RedisUtil.get(wId+"sendMsg");
//        if (msgState != null) {
//            if (msgState != 0) {
//                return Flux.just(OpenResult.error("上次请求结果未返回，请耐心等待或刷新页面，如一直没有返回，则在2分钟后重新发起请求")).map(JSONUtil::toJsonStr);
//            }
//        }
//
//
//        long start = System.currentTimeMillis();
//
//        List<RequestToken> requestTokenList = requestTokenService.lambdaQuery().eq(RequestToken::getSignStatus, 0)
//                .eq(RequestToken::getTokenType, 6)
//                .gt(RequestToken::getBalance, 0).list();
//        if (requestTokenList.size() == 0) {
//            return Flux.just(OpenResult.error("当前没有机器可发送消息，请联系管理员")).map(JSONUtil::toJsonStr);
//        }
//
//        if (ipWhite.getRequestCount() <= 0) {
//            return Flux.just(OpenResult.error("你的余额已经用完！如果想继续可加群聊：237343691，联系群主<br/>\" +\n" +
//                    "                    \"1，打赏1元，赠送20额度，打赏5元赠送110额度<br/>\" +\n" +
//                    "                    \"2，打赏10元，升级为PLUS用户，内部单独绑定一个chatgpt开发者key，支持上下文，如果你需要，可以将chatgpt账号密码和开发者key发给你，相当于10元购chatgpt账号,(保证单独使用，绝无共享)")).map(JSONUtil::toJsonStr);
//        }
//
//        RedisUtil.set(wId+"sendMsg", 1, 120);
//
//        List<RequestRecord> requestRecordList = requestRecordService.lambdaQuery()
//                .eq(RequestRecord::getWid, wId)
//                .eq(RequestRecord::getIsDelete, 0)
//                .eq(RequestRecord::getGroupCode,code)
//                .orderByDesc(RequestRecord::getRequestId)
//                .last("limit 3").list();
//        List<MessageVo> messageVoList = new ArrayList<>();
//        for (RequestRecord requestRecord : requestRecordList) {
//            messageVoList.add(new MessageVo("user",requestRecord.getRequestContent()));
//            messageVoList.add(new MessageVo("assistant",requestRecord.getRespondContent()));
//        }
//        messageVoList.add(new MessageVo("user",URLUtil.decode(msg, Charset.defaultCharset())));
//        log.info("message对象================{}",JSONUtil.parseArray(messageVoList).toString());
//        return Flux.create(sink -> {
//            HttpRequest bodyRequest = HttpRequest.get("http://43.153.26.183/v1/chat/completions")
//                    .header("Content-Type", "application/json")
//                    .header("Authorization", "Bearer "+requestTokenList.get(RandomUtil.getRandom().nextInt(requestTokenList.size())).getSign())
//                    .header("Accept", "text/event-stream")
//                    .body("{\n" +
//                            "    \"messages\": "+JSONUtil.parseArray(messageVoList).toString()+",\n" +
//                            "    \"model\": \"gpt-3.5-turbo\",\n" +
//                            "    \"temperature\": 0.5,\n" +
//                            "    \"top_p\": 1,\n" +
//                            "    \"n\": 1,\n" +
//                            "    \"stream\":true\n" +
//                            "}");
//            HttpResponse responseBody = bodyRequest.executeAsync();
//
//            if (responseBody.isOk()) {
//                try (InputStream inputStream = responseBody.bodyStream();
//                     InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
//                     BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
//                    String line;
//                    while ((line = bufferedReader.readLine()) != null) {
//                        if (line.startsWith("data:")) {
//                            sink.next(line);
//                        }
//                    }
//                    RedisUtil.set(wId+"sendMsg",0,120);
//                } catch (IOException e) {
//                    sink.error(new RuntimeException("Error while reading event data: " + e.getMessage()));
//                } finally {
//                    RedisUtil.set(wId+"sendMsg",0,120);
//                    IoUtil.close(responseBody);
//                }
//            } else {
//                RedisUtil.set(wId+"sendMsg",0,120);
//                sink.error(new RuntimeException("Failed to connect to SSE endpoint."));
//            }
//            sink.complete();
//            long end = System.currentTimeMillis();
//            log.info("当前请求消耗时间：{}ms",end-start);
//        });
//    }

    public DecodedJWT tokenState(String token){
        try {
            return jwtComponent.getTokenInfo(token);
        }catch (Exception e){
            return null;
        }
    }



}